package com.atguigu.tingshu.user.pattern.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.pattern.DeliveryStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2025-08-04 09:23
 */
@Slf4j
@Component(SystemConstant.ORDER_ITEM_TYPE_TRACK)  //采用注解注册到IOC容器Bean的ID默认为类名首字母小写：albumDelivery
public class TrackDelivery implements DeliveryStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    /**
     * 专辑权益发放
     *
     * @param userPaidRecordVo
     */
    @Override
    public void delivery(UserPaidRecordVo userPaidRecordVo) {
        log.info("虚拟物品发货：{},处理声音发货逻辑", userPaidRecordVo.getItemType());
        //2. 处理购买项目类型为声音
        //2.1 根据订单编号查询是否存在购买记录，如果存在则忽略
        Long count = userPaidTrackMapper.selectCount(
                new LambdaQueryWrapper<UserPaidTrack>()
                        .eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo())
                        .select(UserPaidTrack::getId)
        );
        if (count > 0) {
            return;
        }
        //2.2 新增声音购买记录
        //远程调用专辑服务获取声音信息，得到所属专辑ID
        TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
        Long albumId = trackInfo.getAlbumId();
        userPaidRecordVo.getItemIdList().forEach(trackId -> {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(albumId);
            userPaidTrack.setTrackId(trackId);
            userPaidTrackMapper.insert(userPaidTrack);
        });
    }
}
